﻿using Microsoft.AspNetCore.Mvc;
using STF.Blog.Common;
using STF.Blog.IService;
using STF.Blog.WebApp.Areas.ForumManage.Filters;
using STF.Blog.WebApp.Areas.ForumManage.Models.Roles;
using X.PagedList;

namespace STF.Blog.WebApp.Areas.ForumManage.Controllers
{
    [Area("ForumManage")]
    [Login]
    public class RolesController : Controller
    {

        private IRolesService _ir;
        public RolesController(IRolesService ir)
        {
            _ir = ir;
        }

        [HttpGet]
        public async Task<IActionResult> Index(string search, int page = 1)
        {
            search = string.IsNullOrEmpty(search) ? "" : search;
            var data = await _ir.GetByNameAsync(search);

            var RolesList = data.Select(r => new RolesListViewModel 
            {
                Id = r.Id,
                Title = r.Title,
                UpdateTime = r.UpdateTime.ToString("yyyy年MM月dd日")
            }).ToList();

            var pages = await RolesList.ToPagedListAsync(page,PageConfig.PageSize);
            ViewBag.Search = search;
            return View(pages);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id) 
        {
            await _ir.PutTrashAsync(id);
            return Redirect("~/ForumManage/Roles/Index");
        }

        [HttpGet]
        public IActionResult Add() 
        {
            return View(new RolesAddViewModel());
        }

        [HttpPost]
        public async Task<IActionResult> Add(RolesAddViewModel model) 
        {
            if (ModelState.IsValid) 
            {
                await _ir.AddUsersAsync(model.Title);
                return Redirect("~/ForumManage/Roles/Index");
            }
            return View(model);
        }

        [HttpGet]
        public async Task<IActionResult> Update(int id) 
        {
            var data = await _ir.GetByIdAsync(id);

            return View(new RolesUpdateViewModel 
            {
                Id = data.Id,
                Title = data.Title
            });
        }

        [HttpPost]
        public async Task<IActionResult> Update(RolesUpdateViewModel model) 
        {
            await _ir.UpdateUsersAsync(model.Id,model.Title);
            return Redirect("~/ForumManage/Roles/Index");
        }

    }
}
